package com.itheima.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Advice;
import com.itheima.domain.vo.AdviceVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.AdviceService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AdviceManager {

    @Reference
    private AdviceService adviceService;

    @Reference
    private UserInfoService userInfoService;

    /**
     * 分页查询所有反馈信息
     * @return
     */
    public PageBeanVo findAdviceList(Integer pageNum, Integer pageSize) {
        // 1. 查询所有反馈信息
        PageBeanVo pageBeanVo = adviceService.findAdviceList(pageNum , pageSize);
        //3.数据转换
        List<Advice> items = (List<Advice>) pageBeanVo.getItems();
        List<AdviceVo> adviceVoList = new ArrayList<>();

        //数据搬家
        if(CollectionUtil.isNotEmpty( items )){
            for (Advice advice : items) {
                //构建返回值
                AdviceVo adviceVo = new AdviceVo();
                //查询出用户的数据
                UserInfo userInfo = userInfoService.findById(advice.getUserId()); //传入的发布反馈的人的id
                //封装数据
                adviceVo.setUserInfo(userInfo);
                BeanUtil.copyProperties(advice,adviceVo);
                adviceVo.setId(advice.getId().toHexString());
                //放入集合
                adviceVoList.add(adviceVo);
            }
        }
        //4.封装pageBeanVo
        pageBeanVo.setItems(adviceVoList);
        //5.返回
        return pageBeanVo;
    }


    /**
     * 保存反馈：
     * @param advice
     */
    public void saveAdvice(Advice advice) {
        //advice.setUserId(advice.getUserId());
        advice.setUserId(RandomUtil.randomLong(10, 50));  // TODO 暂时随机生成，实际需打开以上注释
        adviceService.save(advice);
    }


    /**
     * 删除反馈：
     */
    public void deleteAdvice(Long userId) {

        adviceService.delete(userId);
    }


    /**
     * 回显反馈：
     * @return
     */
    public AdviceVo showAdvice(Long userId) {

        Advice advice = adviceService.findById(userId);
        //构建返回值
        AdviceVo adviceVo = new AdviceVo();
        //查询出用户的数据
        UserInfo userInfo = userInfoService.findById(advice.getUserId()); //传入的发布反馈的人的id
        //封装数据
        adviceVo.setUserInfo(userInfo);
        BeanUtil.copyProperties(advice,adviceVo);
        adviceVo.setId(advice.getId().toHexString());
        return adviceVo;
    }

}
